<template>
  <view class="container">
    
    <view class="content">
      <view class="section-title">兴趣爱好描述</view>
      <view class="description">
        描述您的兴趣爱好和个人特长，展示您的兴趣范围和个性特点。
        这有助于向招聘者展示您全面的个人形象和可能为团队带来的额外价值。
      </view>
      
      <view class="text-editor">
        <textarea
          v-model="hobby"
          placeholder="请描述您的兴趣爱好和个人特长..."
          :maxlength="maxLength"
          class="editor-area"
        />
        <view class="word-count">{{ hobby.length }}/{{ maxLength }}</view>
      </view>
      
      <view class="tips-section">
        <view class="tips-title">撰写提示：</view>
        <view class="tips-content">
          <view class="tip-item">• 简明扼要地描述您的主要兴趣爱好</view>
          <view class="tip-item">• 重点突出与应聘职位相关的兴趣特长</view>
          <view class="tip-item">• 可以提及您在兴趣领域取得的成就</view>
          <view class="tip-item">• 展示您如何通过兴趣发展了职场中有价值的软技能</view>
        </view>
      </view>
      
      <view class="ai-section" @click="generateContent">
        <image src="/static/images/ai_icon.png" class="ai-icon"></image>
        <view class="ai-text">AI智能生成内容</view>
      </view>
    </view>
    
    <view class="bottom-bar">
      <button class="save-btn" @click="saveHobby">保存</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import NavHeader from '@/components/nav-header.vue'
import { onLoad } from '@dcloudio/uni-app'
import {
  getHobbyDetail,
  addHobby,
  updateHobby,
  generateHobby
} from '@/api/edit/hobby'
import { useResumeStore } from '@/store/resume'
import env from '@/env'
import { useAuthStore } from '@/store/index';
import { mockInterviewWebSocketProcess } from '@/api/ai'
import { useWebSocket } from '@/utils/useWebSocket'

const authStore = useAuthStore();
const statusBarHeight = ref(20)
const hobby = ref('')
const maxLength = 500
const isAdding = ref(true)
const currentId = ref(null)
const resumeStore = useResumeStore()
const isGenerating = ref(false)
const { messages, isConnected, connect, sendMessage, close, onMessage } = useWebSocket(env.websocket)

// 注册WebSocket消息处理函数
onMessage((data) => {
  uni.hideLoading();
  try {
    if (typeof data === 'string') {
      try {
        const parsedData = JSON.parse(data);
        if (parsedData.topic === 'HOBBIES') {
          if (parsedData.content === '[DONE]' || parsedData.content.includes('[DONE]')) {
            isGenerating.value = false;
            uni.hideLoading();
            uni.showToast({
              title: '生成完成',
              icon: 'success'
            });
            return;
          }
          hobby.value += parsedData.content;
          return;
        }
      } catch (e) {
        // 如果不是JSON格式，直接处理字符串
        if (data === '[DONE]' || data.includes('[DONE]')) {
          isGenerating.value = false;
          uni.hideLoading();
          uni.showToast({
            title: '生成完成',
            icon: 'success'
          });
          return;
        }
        hobby.value += data;
      }
    }
  } catch (error) {
    console.error('处理WebSocket消息出错:', error);
  }
});

onLoad(async (options) => {
  if (options.index) {
    isAdding.value = false
    currentId.value = options.index
    await fetchHobbyDetail(options.index)
  } else {
    isAdding.value = true
    hobby.value = ''
  }
})

onMounted(() => {
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight
  
  // 启动时先尝试连接WebSocket
  try {
    connect().then(() => {
      console.log('WebSocket连接成功，可以接收消息');
    }).catch(err => {
      console.error('WebSocket连接失败:', err);
    });
  } catch (e) {
    console.error('连接WebSocket异常:', e);
  }
})

onUnmounted(() => {
  // 关闭WebSocket连接
  close();
  if (isGenerating.value) {
    isGenerating.value = false;
  }
})

async function fetchHobbyDetail(id) {
  try {
    uni.showLoading({ title: '加载中...' })
    const res = await getHobbyDetail(id)
    if (res.code === 200 && res.data) {
      hobby.value = res.data.hobbyDescription || ''
    }
  } catch (e) {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

const saveHobby = async () => {
  if (!hobby.value.trim()) {
    uni.showToast({ title: '请输入兴趣爱好', icon: 'none' })
    return
  }
  try {
    uni.showLoading({ title: '保存中...' })
    let res
    // const params = { hobbyDescription: hobby.value, resumeId: '1916784587136589826' }
    const params = { hobbyDescription: hobby.value, resumeId: resumeStore.resumeId }
    if (isAdding.value) {
      res = await addHobby(params)
    } else {
      params.id = currentId.value
      res = await updateHobby(params)
    }
    if (res.code === 200) {
      uni.showToast({ title: '保存成功', icon: 'success' })
      setTimeout(() => { uni.navigateBack() }, 1500)
    } else {
      uni.showToast({ title: res.msg || '保存失败', icon: 'none' })
    }
  } catch (e) {
    uni.showToast({ title: '保存失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

const generateContent = async () => {
  try {
    // 避免重复请求
    if (isGenerating.value) {
      return;
    }
    
    isGenerating.value = true;
    hobby.value = ''; // 清空之前的内容
    
    uni.showLoading({
      title: 'AI生成中...'
    });
    
    // 创建请求数据
    const requestData = {
      type: 'HOBBIES',
      aiResumeHobbiesBo: {
        resumeId: resumeStore.resumeId
      }
    };
    
    // 检查WebSocket连接状态
    if (!isConnected.value) {
      console.log('WebSocket未连接，尝试连接...');
      await connect();
      console.log('WebSocket连接已建立');
    } else {
      console.log('WebSocket已连接，状态正常');
    }
    
    // 确保WebSocket已连接后，调用HTTP接口触发后端推送消息
    console.log('准备调用HTTP接口触发后端推送...');
    
    // 调用HTTP接口触发后端推送WebSocket消息
    mockInterviewWebSocketProcess(requestData).then(res => {
      // 如果很长时间没收到WebSocket消息，可能后端未正确推送，此时使用HTTP响应结果
      setTimeout(() => {
        if (isGenerating.value && !hobby.value) {
          console.log('未收到WebSocket消息，使用传统方式');
        }
      }, 5000); // 5秒后检查
      
    }).catch(err => {
      console.error('调用HTTP接口失败:', err);
      isGenerating.value = false;
      uni.hideLoading();
      uni.showToast({
        title: '生成失败',
        icon: 'none'
      });
    });
    
  } catch (error) {
    console.error('生成兴趣爱好失败', error);
    isGenerating.value = false;
    uni.hideLoading();
    uni.showToast({
      title: '生成失败',
      icon: 'none'
    });
  }
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.content {
  flex: 1;
  padding: 30rpx;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 6px;
}

.description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 30rpx;
}

.text-editor {
  position: relative;
  margin-bottom: 35px;
}

.editor-area {
  width: 100%;
  height: 320rpx;
  padding: 20rpx;
  box-sizing: border-box;
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  line-height: 1.6;
  background-color: #fff;
}

.word-count {
  position: absolute;
  bottom: -20px;
  right: 10px;
  font-size: 12px;
  color: #999;
}

.tips-section {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 30rpx;
}

.tips-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.tips-content {
  font-size: 26rpx;
  color: #666;
}

.tip-item {
  margin-bottom: 10rpx;
  line-height: 1.5;
}

.ai-section {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f7ff;
  padding: 20rpx;
  border-radius: 8rpx;
  margin: 30rpx 0;
  border: 1px dashed #b8d8ff;
}

.ai-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}

.ai-text {
  font-size: 28rpx;
  color: #4080ff;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 70px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  z-index: 9;
}

.save-btn {
  width: 100%;
  height: 44px;
  line-height: 44px;
  background-color: #5ac725;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 500;
  border-radius: 22px;
}
</style> 